// pages/zpxx_fb/pxbb.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgs: [],
    array6: [],
    index6: 0,
    multiArray: [['小学', '初中', '高中'], ['一年级', '二年级', '三年级', '四年级', '五年级', '六年级']],
    multiIndex: [0, 0],
    chooseAddress:'',
    latitude: 0,
    longitude: 0,
    checked: true,
    user:[],
    city:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _this=this;
    //获取课程类型
    this.getCourse();
    //检测用户是否登录
    var user = wx.getStorageSync("userInfo")
    var city = wx.getStorageSync("city")
    if(user){
      _this.setData({
        user:user,
        city: city
      })
    }else{
      wx.showToast({
        title: "请先登录",
        icon: 'none',
        duration: 2000
      })
      //返回上一页
      setTimeout(function () {
        wx.navigateTo({
          url: '/pages/user/user'
        })
      }, 2000)
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //获取课程
  getCourse:function(){
      let _this=this;
    app.wxRequest('post','/Samecity/CommonCategory/getCourse',[],function(res){
        if(res.data.code==0){
            _this.setData({
              array6:res.data.data
            })
        }else{
          wx.showToast({
            title: "获取课程失败",
            icon: 'none',
            duration: 2000
          })
        }
    })
  },

//获取企业地图信息
onChangeAddress: function () {
  var _page = this;
  wx.chooseLocation({
    success: function (res) {
      console.log(res);
      _page.setData({
        chooseAddress: res.name + '-' +res.address,
        latitude: res.latitude,
        longitude: res.longitude
      });
    },
    fail: function (err) {
      console.log(err);
    }
  });
},
  //年级多列选择器：
  bindMultiPickerChange: function (e) {
    console.log(e.detail);
    this.setData({
      multiIndex: e.detail.value
    })
  },

  //科目选择器：
  bindPickerChange6: function (e) {
    this.setData({
      index6: e.detail.value
    })
  },

  //图片上传
  chooseImg: function (e) {
    let that = this;
    var imgs = that.data.imgs;
    var imgsLength = imgs.length
    wx.chooseImage({
      count: 9 - imgsLength,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var filePaths = res.tempFilePaths
        var filePathsLength = filePaths.length;
        var failNum = 0;
        for (var i = 0; i < filePathsLength; i++) {
          wx.uploadFile({
            url: app.globalData.theUrl1 + '/Samecity/Upload/uploadFile',
            filePath: filePaths[i],
            name: 'fileData',
            formData: {},
            success: (successBack) => {
              var imgs = that.data.imgs;
              var data = JSON.parse(successBack.data)
              if (data.code == 0) {
                imgs.push(data.url);
                that.setData({
                  imgs: imgs
                })
              } else {
                failNum++;
              }
            },
            fail: (failBack) => {
              failNum++;
            },
          });
        }
        wx.showToast({
          title: '总共' + filePathsLength + '张上传成功,' + failNum + '张上传失败！',
          icon: 'none'
        });
      }
    });
  },
  // 删除图片
  deleteImg: function (e) {
    var imgs = this.data.imgs;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    this.setData({
      imgs: imgs
    });
  },
  // 预览图片
  previewImg: function (e) {
    var index = e.currentTarget.dataset.index;
    var imgs = this.data.imgs;
    wx.previewImage({
      current: imgs[index],
      urls: imgs
    })
  },
  //条款选项
  checkboxChange:function(e){
    let _this=this;
      _this.setData({
        checked: _this.data.checked != false ? false : true
      })
  },
  //提交form
  formSub: function (e) {
    let _this = this;
    let data = _this.data;
    var fromData = e.detail.value
    //获取经纬度
    fromData.latitude = data.latitude
    fromData.longitude = data.longitude
    fromData.location = data.chooseAddress
    fromData.images = data.imgs.join(',')
    fromData.training_grade = data.multiArray[0][data.multiIndex[0]] + ',' + data.multiArray[1][data.multiIndex[1]]
    fromData.course_type = data.array6[data.index6].id
    fromData.checked = data.checked
    fromData.uid = data.user.id
    fromData.city = data.city
    fromData.type = 1
    //验证必填数据
    var errorInfo=true;
    if (!fromData.corporate_name){
      errorInfo="请填写公司名称"
    } else if (!fromData.location || !fromData.longitude || !fromData.latitude){
      errorInfo = "请选择地址"
    } else if (!fromData.tuition) {
      errorInfo = "请填写学费"
    } else if (!fromData.explain) {
      errorInfo = "请填写备注"
    } else if (!fromData.images) {
      errorInfo = "请至少上传一张图片"
    } else if (!fromData.name) {
      errorInfo = "请填写联系人名称"
    } else if (!fromData.tel || !(/^1[34578]\d{9}$/.test(fromData.tel))) {
      errorInfo = "请检查手机号是否正确"
    } else if (!fromData.checked) {
      errorInfo = "请勾选平台协议"
    }
    if (errorInfo === true){
      //提交数据
      app.wxRequest('POST', '/Samecity/Train/train',fromData,function(res){
          if(res.data.code==1){
            wx.showToast({
              title: "发布成功",
              icon: 'none',
              duration: 2000
            })
            //返回上一页
            setTimeout(function () {
              wx.navigateBack();
            }, 2000)
          }else{
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            })
          }
      },function(err){
        console.log(err)
      })
    }else{
      wx.showToast({
        title: errorInfo,
        icon: 'none',
        duration: 2000
      })
    }
  },
})